﻿using FrameWorkSong;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class AreaCreatDemo : MonoBehaviour
{
    public Material material;
    MeshAreaCreate meshAreaCreate;
    // Start is called before the first frame update
    void Start()
    {
        Vector3[] vertices = new Vector3[6];
        vertices[5] = new Vector3(-2.5f, 0, -2.5f);
        vertices[4] = new Vector3(2.5f,1, -2.5f);
        vertices[3] = new Vector3(4.5f,0, 2.5f);
        vertices[2] = new Vector3(0.5f,3, 4.5f);
        vertices[1] = new Vector3(-3.5f,0, 2.5f);
        vertices[0] = new Vector3(0, 0, 0);
        
        meshAreaCreate = new MeshAreaCreate(vertices, 22.5f);
        MeshFilter filter = gameObject.AddComponent<MeshFilter>();
        MeshRenderer renderer = gameObject.AddComponent<MeshRenderer>();
        renderer.sharedMaterial = material;
        filter.mesh = meshAreaCreate.mesh;


        //凹多边形创建
        //  CreatTest(vertices);
    }

    void CreatTest(Vector3[] vertices)
    {
        MeshFilter filter = gameObject.AddComponent<MeshFilter>();
        // 多边形2d轮廓线的输入点
        List<Vector2> points = new List<Vector2>();
        for (int i = 0; i < vertices.Length; i++)
        {
            points.Add(new Vector2(vertices[i].x, vertices[i].z));
        }



        // 构建Polygon2D
        Polygon2D polygon = Polygon2D.Contour(points.ToArray());

        // 使用Polygon2D和阈值角(推荐18f ~ 27f)构建Triangulation2D
        Triangulation2D triangulation = new Triangulation2D(polygon, 22.5f);

        // 在Triangulation2D实例中用三角形构建一个网格
        Mesh mesh = triangulation.Build();
        int length = mesh.vertices.Length;
        for (int i = 0; i < length; i++)
        {
            Debug.Log(i + ":" + mesh.vertices[i]);
        }
        mesh.vertices = vertices;

        filter.mesh = mesh;

        MeshRenderer renderer = gameObject.AddComponent<MeshRenderer>();
        //renderer.sharedMaterial = new Material(Shader.Find("Standard"));
        renderer.sharedMaterial = material;
    }
}
